import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/Xwidgets/video_thumb.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/goods_detail/goodsPhotoGalleryPage.dart';
import 'package:yp/pages/mall_app/goods_detail/ratting_widget.dart';
import 'package:yp/utils/videoplayer/video_player_plus.dart';

import 'logic.dart';

class GoodsCommentListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _GoodsCommentListPageState();
}

class _GoodsCommentListPageState extends State<GoodsCommentListPage> {
  final logic = Get.put(GoodsCommentLogic());
  final state = Get.find<GoodsCommentLogic>().state;

  _GoodsCommentListPageState() {
    logic.styleNumId = Get.arguments["styleNumId"];
  }

  int _getCommentCount() {
    return state.commentList == null ? 0 : state.commentList.length;
  }

  @override
  void initState() {
    super.initState();
    logic.requestComment(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            color: Color(0xFF333333),
          ),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          '全部评价',
          style: TextStyle(
            fontSize: 17,
            color: Color(0xFF030303),
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      body: GetBuilder<GoodsCommentLogic>(
        builder: (logic) {
          return SmartRefresher(
            enablePullDown: false,
            enablePullUp: true,
            header: WaterDropHeader(),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                if (mode == LoadStatus.idle) {
                  body = Text("上拉加载更多");
                } else if (mode == LoadStatus.loading) {
                  body = CupertinoActivityIndicator();
                } else if (mode == LoadStatus.failed) {
                  body = Text("加载失败！点击重试！");
                } else if (mode == LoadStatus.canLoading) {
                  body = Text("释放以加载更多");
                } else {
                  body = Text("没有更多了");
                }
                return Container(
                  height: 55.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: state.refreshController,
            onLoading: logic.onLoadMoreGoodsList,
            child: ListView.builder(
              itemCount: _getCommentCount(),
              itemBuilder: (context, index) {
                var comment = state.commentList[index];
                return _commentItem(comment);
              },
            ),
          );
        },
      ),
    );
  }

  Widget _commentItem(var comment) {
    String logoUrl = comment['logo'] ?? "";
    String userName = comment['nick_name'] ?? "";
    int score = comment['result'] == null ? 0 : num.parse(comment['result']);
    String commentContent = comment['content'];
    String picsString = comment['list_video'] ?? "";
    List<String> picList = [];
    if (picsString != null && picsString.isNotEmpty) {
      picList = picsString.split(',');
    }

    String rateString = comment['rate_pic'] ?? "";
    List<String> rateList = [];
    if (rateString != null && rateString.isNotEmpty) {
      rateList = rateString.split(',');
    }

    if (rateList.length > 0) {
      picList.addAll(rateList);
    }
    var appendObj = comment['append'];
    var hasAppend = appendObj != null;
    List<String> appendPicList = [];
    if (hasAppend) {
      String appendPicsString = appendObj['append_rate_pic'] ?? "";
      if (appendPicsString != null && appendPicsString.isNotEmpty) {
        appendPicList = appendPicsString.split(',');
      }
      print('**********************************');
      print('$appendObj');
      print(appendPicList.length);
      print('**********************************');
    }

    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Padding(
                padding: const EdgeInsets.all(11.0),
                child: ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(16)),
                  child: CachedNetworkImage(
                    imageUrl: logoUrl,
                    width: 32,
                    height: 32,
                    fit: BoxFit.fill,
                    errorWidget: (context, url, error) {
                      return Image.asset(
                        'assets/images/group_mumber.png',
                        width: 32,
                        height: 32,
                        fit: BoxFit.fill,
                      );
                    },
                  ),
                ),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      comment["anony"] == 1 ? '匿名用户' : userName,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14,
                        color: const Color(0xFF222222),
                      ),
                    ),
                    Ratting(score: score),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(10.0),
                child: Text(
                  comment['created_time'],
                  style: TextStyle(
                    fontSize: 11,
                    color: Color(0xFFAAAAAA),
                  ),
                ),
              ),
            ],
          ),
          Padding(
            padding:
                const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 7),
            child: Text(
              commentContent,
              style: TextStyle(
                fontSize: 12,
                color: Color(0xFF222222),
              ),
            ),
          ),
          if (picList.length > 0)
            Visibility(
              visible: picList.isNotEmpty,
              child: GridView.builder(
                padding: EdgeInsets.symmetric(horizontal: 10),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 10,
                  crossAxisSpacing: 10,
                  childAspectRatio: 1,
                ),
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                itemCount: picList.length,
                itemBuilder: (context, index) {
                  if (picList[index].contains(".mp4")) {
                    return GestureDetector(
                      onTap: () {
                        Get.to(
                          VideoPlayerPlus(
                            VideoPlayerController.network(picList[index]),
                          ),
                        );
                      },
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Container(
                              width: double.infinity,
                              height: double.infinity,
                              margin: EdgeInsets.zero,
                              color: Colors.grey,
                              child: VideoApp(videoUrl: (picList[index]))),
                          Positioned(
                            child: Icon(Icons.play_circle_fill,
                                color: Colors.white),
                          )
                        ],
                      ),
                    );
                  }
                  return ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    // child: Image.network(
                    //   picList[index],
                    //   width: double.infinity,
                    //   height: double.infinity,
                    //   fit: BoxFit.fill,
                    // ),
                    child: GestureDetector(
                      onTap: () {
                        Get.to(goodsPhotoGalleryPage(
                          picList
                              .where((element) => !element.contains(".mp4"))
                              .toList(),
                          currentIndex: index -
                              picList
                                  .where((element) => element.contains(".mp4"))
                                  .toList()
                                  .length,
                        ));
                      },
                      child: cacheImage(
                        imageUrl: picList[index],
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                      ),
                    ),
                  );
                },
              ),
            ),
          if (comment['reply_content'] != null &&
              comment['reply_content'] != '')
            Padding(
              padding: EdgeInsets.only(left: 10, right: 10),
              child: Container(
                color: Colors.transparent,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _divider(1, color: Color(0xffeeeeee)),
                    SizedBox(height: setWidth(20)),
                    Text(
                      comment['reply_time'],
                      style: TextStyle(
                        color: Color(0xff333333),
                        fontSize: 15,
                      ),
                    ),
                    SizedBox(height: setWidth(10)),
                    Text.rich(
                      TextSpan(
                        children: [
                          TextSpan(
                            text: '客服回复：',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: Color(0xFF222222),
                            ),
                          ),
                          TextSpan(
                            text: comment['reply_content'],
                            style: TextStyle(
                              color: Color(0xff333333),
                              fontSize: 15,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          // Container(
          //   color: Color(0xFFF7F7F7),
          //   margin: EdgeInsets.all(10),
          //   padding: EdgeInsets.only(left: 15, right: 12, top: 13, bottom: 13),
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       Row(
          //         children: [
          //           Text(
          //             "客服回复：",
          //             style: TextStyle(
          //               fontSize: 14,
          //               fontWeight: FontWeight.w500,
          //               color: Color(0xFF222222),
          //             ),
          //           ),
          //           Spacer(),
          //           Text(
          //             "2019年12月21日 13:21:21",
          //             style: TextStyle(fontSize: 11, color: Color(0xFFB3B3B3)),
          //           ),
          //         ],
          //       ),
          //       Text(
          //         "感谢您对本产品的大力支持和厚爱，希望您的皮肤越来越光洁丝滑，祝您购物愉快么么哒～",
          //         style: TextStyle(
          //           fontSize: 12,
          //           color: Color(0xFF222222),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          hasAppend == false
              ? Container()
              : Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('追评', style: TextStyle(color: Colors.orange)),
                        Container(
                            margin: EdgeInsets.symmetric(vertical: 5),
                            child: Text(appendObj['append_content'],
                                style: TextStyle(
                                    fontSize: 12, color: Color(0xFF222222)))),
                        if (appendPicList.length > 0)
                          Visibility(
                              visible: appendPicList.isNotEmpty,
                              child: GridView.builder(
                                  padding: EdgeInsets.symmetric(horizontal: 10),
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 4,
                                    mainAxisSpacing: 10,
                                    crossAxisSpacing: 10,
                                    childAspectRatio: 1,
                                  ),
                                  physics: NeverScrollableScrollPhysics(),
                                  shrinkWrap: true,
                                  itemCount: appendPicList.length,
                                  itemBuilder: (context, index) {
                                    if (appendPicList[index].contains(".mp4")) {
                                      return GestureDetector(
                                        onTap: () {
                                          Get.to(
                                            VideoPlayerPlus(
                                              VideoPlayerController.network(
                                                  appendPicList[index]),
                                            ),
                                          );
                                        },
                                        child: Stack(
                                          alignment: Alignment.center,
                                          children: [
                                            Container(
                                                width: double.infinity,
                                                height: double.infinity,
                                                margin: EdgeInsets.zero,
                                                color: Colors.grey,
                                                child: VideoApp(
                                                    videoUrl: (appendPicList[
                                                        index]))),
                                            Positioned(
                                              child: Icon(
                                                  Icons.play_circle_fill,
                                                  color: Colors.white),
                                            )
                                          ],
                                        ),
                                      );
                                    }
                                    return ClipRRect(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(5)),
                                        // child: Image.network(
                                        //   picList[index],
                                        //   width: double.infinity,
                                        //   height: double.infinity,
                                        //   fit: BoxFit.fill,
                                        // ),
                                        child: GestureDetector(
                                          onTap: () {
                                            Get.to(goodsPhotoGalleryPage(
                                              appendPicList
                                                  .where((element) =>
                                                      !element.contains(".mp4"))
                                                  .toList(),
                                              currentIndex: appendPicList
                                                  .where((element) =>
                                                      !element.contains(".mp4"))
                                                  .toList().indexWhere((element) => element == appendPicList[index]),
                                            ));
                                          },
                                          child: cacheImage(
                                            imageUrl: appendPicList[index],
                                            width: double.infinity,
                                            height: double.infinity,
                                            fit: BoxFit.cover,
                                          ),
                                        ));
                                  }))
                      ]),
                )
        ],
      ),
    );
  }

  //分隔控件
  Widget _divider(double height, {Color color}) {
    return Container(
      width: double.infinity,
      height: height,
      color: color ?? Color(0xFFF3F4F6),
    );
  }
}
